package pc

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

//获取玩家列表信息
func ListPlayerInfo(p ListParams, u ListCtUserParams, op OrderParams, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := " 1=1 "
	if u.Phone != "" {
		where = where + fmt.Sprintf(" AND phone LIKE '%v'", "%"+u.Phone+"%")
	}
	if u.Name != "" {
		where = where + fmt.Sprintf(" AND nickname LIKE '%v'", "%"+u.Name+"%")
	}
	if len(u.Uid) > 0 {
		uidStr := Join(u.Uid, ",")
		where = where + fmt.Sprintf(" AND uid IN (%v)", uidStr)
	}

	orderName := " rtime " //默认以注册时间倒序
	order := GetOrderSort("DESC", op.Order)
	if op.OrderName != "" {
		orderName = op.OrderName
	}

	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			%v
		ORDER BY
			%v %v
		LIMIT ?,?
		`, TableClientUser, where, orderName, order)
	o := NewOrm(multiOrm)
	var user []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&user)
	if CheckError(err) {
		return nil, 0, err
	}
	for _, v := range user {
		v["play_num"] = statPlayerPlayNum(v["uid"], o)
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v WHERE %v`, TableClientUser, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	return user, count, err
}

//获取玩家一共玩了多少局游戏
func statPlayerPlayNum(uid interface{}, multiOrm ...orm.Ormer) int64 {
	o := NewOrm(multiOrm, DBChess)
	sql := fmt.Sprintf(`
		SELECT
			IF(SUM(play_num) is NULL,0,SUM(play_num)) AS play_num
		FROM
			%v
		WHERE
			uid = %v
	`, TableUserGame, uid)
	var playNum int64
	o.Raw(sql).QueryRow(&playNum)
	return playNum
}

//玩家战绩记录
func PlayerRecord(p ListParams, t ListDayParams, uid int64, gameType, playType int, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	condition := fmt.Sprintf("rl.uid = %v", uid)
	if t.StartTime > 0 && t.EndTime > t.StartTime {
		condition = condition + fmt.Sprintf(" AND rl.jointime >= %v AND rl.jointime < %v", t.StartTime, t.EndTime)
	}
	if gameType != 0 && playType != 0 {
		condition = condition + fmt.Sprintf(" AND r.gametype = %v AND r.playtype = %v ", gameType, playType)
	}

	sql := fmt.Sprintf(`
		SELECT
			r.tableid,r.starttime,r.endtime,r.passwd,r.gametype,r.playtype,
			r.basescore,r.gameinfo,r.dueround,r.consume,r.createtime
		FROM
			%v AS rl
		LEFT JOIN
			%v AS r
		ON r.tableid= rl.tableid
		WHERE
			%v
		ORDER BY
			r.tableid DESC
		LIMIT ?,?`,
		TableRoomLog, TableRoom, condition)
	o := NewOrm(multiOrm, DBChess)
	var room []orm.Params
	n, err := o.Raw(sql, limit, p.PageSize).Values(&room)
	if err != nil || n == 0 { //没有数据可查
		return room, 0, err
	}
	for _, v := range room {
		v["game_id"] = GenGameId(v["gametype"], v["playtype"])
	}
	sql = fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v AS rl
		LEFT JOIN
			%v AS r
		ON r.tableid= rl.tableid
		WHERE
			%v`,
		TableRoomLog, TableRoom, condition)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return room, 0, err
	}
	return room, count, nil
}

// 通过桌子ID获得游戏每局信息
func RecordDetail(tableId int64, multiOrm ...orm.Ormer) ([]orm.Params, error) {
	var (
		startTime int64
		endTime   int64
	)
	sql := fmt.Sprintf(`
		SELECT starttime,endtime FROM %v WHERE tableid = %v `, TableRoom, tableId)
	var res []orm.Params
	o := NewOrm(multiOrm, DBChess)
	err := o.Raw(sql).QueryRow(&startTime, &endTime)
	if CheckError(err) {
		return res, err
	}
	if startTime == 0 { //开了房在那还没有开始打，所以没有战绩可查
		return res, nil
	}

	bTable := GetTableByTimestamp(TableDayGame, startTime)
	eTable := GetTableByTimestamp(TableDayGame, endTime)

	where := fmt.Sprintf(" WHERE tid=%v ", tableId)
	if bTable == eTable || endTime < startTime { //打牌开始时间与结束时间在同一天, endTime < startTime 表示已经开打了，但还没有结束，所以endTime = 0
		sql = fmt.Sprintf("SELECT * FROM %v %v", bTable, where)
	} else { //跨天，一般跨一天，跨多天的几乎不可能出现，出现了就只有显示开始的一天与结束的那天，无所谓了
		sql = fmt.Sprintf("(SELECT * FROM %v %v ) UNION (SELECT * FROM %v %v)", bTable, where, eTable, where)
	}
	og := NewDBOrm(DBChessLog)
	_, err = og.Raw(sql).Values(&res)
	return res, err
}

//玩家登录详细情况
func PlayerLoginLog(p ListParams, t ListDayParams, uid int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	condition := fmt.Sprintf("uid = %v", uid)
	if t.StartTime > 0 && t.EndTime > t.StartTime {
		condition = fmt.Sprintf("uid = %v AND login_time >= %v AND login_time <= %v ", uid, t.StartTime, t.EndTime)
	}
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			%v
		ORDER BY
			login_time DESC
		LIMIT ?,?`,
		TablePlayerLoginLog, condition)
	o := NewOrm(multiOrm, DBChessLog)
	var log []orm.Params
	n, err := o.Raw(sql, limit, p.PageSize).Values(&log)
	if err != nil || n == 0 { //没有数据可查
		return log, 0, err
	}
	sql = fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE
			%v`,
		TablePlayerLoginLog, condition)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return log, 0, err
	}
	return log, count, nil
}

//玩家钻石购买记录
func ListPlayerCardRecord(p ListCardParams, multiOrm ...orm.Ormer) ([]*CardRecord, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf(" player_id = %v ", p.PlayerId)
	if p.Type != 0 {
		where = where + fmt.Sprintf(" AND type = %v ", p.Type)
	}
	sql := fmt.Sprintf(`
		SELECT
			id,agent_id,player_id,card_num,amount,type,pay_type,create_time
		FROM
			%v
		WHERE
			%v
		ORDER BY
			id DESC
		LIMIT ?,?
		`, TableH5CardRecord, where)
	o := NewOrm(multiOrm, DBChessCenter)
	var cr []*CardRecord
	_, err := o.Raw(sql, limit, p.PageSize).QueryRows(&cr)
	if CheckError(err) {
		return nil, 0, err
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v WHERE %v`, TableH5CardRecord, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return nil, 0, err
	}
	return cr, count, nil
}
